use clap::{Arg, ArgMatches, Command};

use crate::environment::environment;
use crate::index::index;

pub(super) const NAME: &'static str = "use";

pub(super) fn new() -> Command {
    let mut command = Command::new(NAME).about("切换全局环境工具");
    command = command.arg(Arg::new("name").required(true).help("工具名称"));
    command = command.arg(Arg::new("version").required(true).help("工具版本"));

    command
}

pub(super) fn action(args: &ArgMatches) {
    let name = args.get_one::<String>("name").unwrap();
    let software = index::index().get(name.as_str());
    if software.is_none() {
        println!("未知的工具名称: {}", name);

        return;
    }

    let software = software.unwrap();

    let version_name = args.get_one::<String>("version").unwrap();
    let version = software.get_version(version_name);
    if version.is_none() {
        println!("工具[{}]未找到版本[{}]配置，请更新本地索引或反馈此问题", name, version_name);

        return;
    }

    let result = environment::global_mut().switch_to(name.to_string(), version_name.to_string());
    if result.is_err() {
        println!("切换工具版本失败: {}", result.unwrap_err())
    }
}